/**
 * Editor Performance Hook
 * 编辑器性能优化 Hook
 */
import { useEffect, useRef, useCallback, useMemo } from 'react';
import { debounce, throttle, rafThrottle, PerformanceMonitor } from '../utils/performance-utils';

interface UseEditorPerformanceOptions {
  onChangeDelay?: number; // onChange 防抖延迟
  onScrollThrottle?: number; // 滚动节流延迟
  enablePerformanceLogging?: boolean; // 是否启用性能日志
}

export function useEditorPerformance(options: UseEditorPerformanceOptions = {}) {
  const {
    onChangeDelay = 300,
    onScrollThrottle = 100,
    enablePerformanceLogging = false
  } = options;

  const monitorRef = useRef<PerformanceMonitor | null>(null);

  // 初始化性能监控
  useEffect(() => {
    if (enablePerformanceLogging) {
      monitorRef.current = new PerformanceMonitor();
    }
  }, [enablePerformanceLogging]);

  // 性能标记
  const mark = useCallback((name: string) => {
    if (enablePerformanceLogging && monitorRef.current) {
      monitorRef.current.mark(name);
    }
  }, [enablePerformanceLogging]);

  // 性能测量
  const measure = useCallback((name: string): number => {
    if (enablePerformanceLogging && monitorRef.current) {
      return monitorRef.current.measure(name);
    }
    return 0;
  }, [enablePerformanceLogging]);

  // 创建防抖的 onChange 处理器
  const createDebouncedOnChange = useCallback(
    <T extends (...args: any[]) => any>(handler: T) => {
      return debounce(handler, onChangeDelay);
    },
    [onChangeDelay]
  );

  // 创建节流的滚动处理器
  const createThrottledScroll = useCallback(
    <T extends (...args: any[]) => any>(handler: T) => {
      return throttle(handler, onScrollThrottle);
    },
    [onScrollThrottle]
  );

  // 创建 RAF 节流的处理器（用于动画）
  const createRafThrottled = useCallback(
    <T extends (...args: any[]) => any>(handler: T) => {
      return rafThrottle(handler);
    },
    []
  );

  // 批量 DOM 更新
  const batchDOMUpdates = useCallback((updates: () => void) => {
    // 使用 requestAnimationFrame 批量处理 DOM 更新
    requestAnimationFrame(() => {
      mark('dom-updates');
      updates();
      measure('dom-updates');
    });
  }, [mark, measure]);

  // 延迟执行（使用 requestIdleCallback 或 setTimeout）
  const scheduleIdleTask = useCallback((task: () => void, timeout?: number) => {
    if ('requestIdleCallback' in window) {
      return (window as any).requestIdleCallback(task, { timeout });
    } else {
      return setTimeout(task, 1);
    }
  }, []);

  // 取消延迟任务
  const cancelIdleTask = useCallback((id: number) => {
    if ('cancelIdleCallback' in window) {
      (window as any).cancelIdleCallback(id);
    } else {
      clearTimeout(id);
    }
  }, []);

  return {
    mark,
    measure,
    createDebouncedOnChange,
    createThrottledScroll,
    createRafThrottled,
    batchDOMUpdates,
    scheduleIdleTask,
    cancelIdleTask
  };
}

/**
 * 虚拟列表 Hook
 * 用于优化长列表渲染
 */
interface UseVirtualListOptions {
  itemHeight: number;
  containerHeight: number;
  overscan?: number;
}

export function useVirtualList<T>(
  items: T[],
  options: UseVirtualListOptions
) {
  const { itemHeight, containerHeight, overscan = 3 } = options;
  const [scrollTop, setScrollTop] = useState(0);

  // 计算可见范围
  const { startIndex, endIndex, offsetY, visibleItems } = useMemo(() => {
    const startIndex = Math.max(0, Math.floor(scrollTop / itemHeight) - overscan);
    const visibleItems = Math.ceil(containerHeight / itemHeight);
    const endIndex = Math.min(
      items.length - 1,
      startIndex + visibleItems + overscan * 2
    );
    const offsetY = startIndex * itemHeight;

    return { startIndex, endIndex, offsetY, visibleItems };
  }, [scrollTop, itemHeight, containerHeight, items.length, overscan]);

  // 可见项目
  const visibleItemsData = useMemo(() => {
    return items.slice(startIndex, endIndex + 1).map((item, index) => ({
      item,
      index: startIndex + index,
      offsetY: (startIndex + index) * itemHeight
    }));
  }, [items, startIndex, endIndex, itemHeight]);

  // 滚动处理器（节流）
  const handleScroll = useCallback(
    rafThrottle((e: React.UIEvent<HTMLElement>) => {
      setScrollTop(e.currentTarget.scrollTop);
    }),
    []
  );

  // 总高度
  const totalHeight = items.length * itemHeight;

  return {
    visibleItems: visibleItemsData,
    totalHeight,
    handleScroll,
    startIndex,
    endIndex
  };
}

/**
 * 代码分割懒加载 Hook
 */
export function useLazyLoad<T>(
  loader: () => Promise<T>,
  fallback?: T
): { data: T | null; loading: boolean; error: Error | null } {
  const [data, setData] = useState<T | null>(fallback || null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<Error | null>(null);

  useEffect(() => {
    let cancelled = false;

    setLoading(true);
    loader()
      .then((result) => {
        if (!cancelled) {
          setData(result);
          setLoading(false);
        }
      })
      .catch((err) => {
        if (!cancelled) {
          setError(err);
          setLoading(false);
        }
      });

    return () => {
      cancelled = true;
    };
  }, [loader]);

  return { data, loading, error };
}

// 导入 useState
import { useState } from 'react';
